//
//  AZPeripheralViewController.m
//  AZBLE
//
//  Created by AZ-Mac on 2017/4/28.
//  Copyright © 2017年 AZ-Mac. All rights reserved.
//

#import "AZPeripheralViewController.h"
#import "BLETool.h"
#import "AZProgressHUD.h"
#import "AZPeripheralInfoModel.h"
#import "AZServiceCell.h"
#import "AZPeripheralInfoModel.h"
#import "AZProgressHUD.h"
#import "AZCharacteristicViewController.h"
@interface AZPeripheralViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *peripheralInfoTableView;
@property(strong,nonatomic)BLETool *ble;
@property(strong,nonatomic) NSMutableArray *services;
@end
@implementation AZPeripheralViewController
static NSString *serviceCell = @"serviceCell";
- (NSMutableArray *)services
{
    if(!_services)
    {
        _services = [NSMutableArray array];
    }
    return _services;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.ble = [BLETool sharedBLETool];
    self.ble.cMgr.delegate = self;
    [self.ble.cMgr connectPeripheral:self.currPeripheral options:nil];
    [self initUI];
}
- (void)initUI
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = [NSString stringWithFormat:@"%@",self.currPeripheral.name];
    self.peripheralInfoTableView.delegate = self;
    self.peripheralInfoTableView.dataSource = self;
    
    [self.peripheralInfoTableView registerNib:[UINib nibWithNibName:@"AZServiceCell" bundle:nil] forCellReuseIdentifier:serviceCell];
}
/*
 *  外设连接成功
 */
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    NSLog(@">>>连接到名称为（%@）的设备-成功",peripheral.name);
    [AZProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@">>>连接到名称为（%@）的设备-成功",peripheral.name]];
    //停止扫描
    [self.ble.cMgr stopScan];
    //设置的蓝牙外设peripheral代理CBPeripheralDelegate
    [peripheral setDelegate:self];

    [peripheral discoverServices:nil];
}
/*
 * 扫描服务
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error)
    {
        NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
        return;
    }
    
    //扫描蓝牙特征
    for (CBService *service in peripheral.services) {
        
        AZPeripheralInfoModel *model = [AZPeripheralInfoModel new];
        model.serviceUUID = service.UUID;
        [self.services addObject:model];
        
        //扫描蓝牙特征
        [peripheral discoverCharacteristics:nil forService:service];
    }
    
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self.peripheralInfoTableView reloadData];
    });
}
/*
 * 外设发现service的特征
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    for (int line = 0;line <self.services.count;line++) {
        
        AZPeripheralInfoModel *model = self.services[line];
        
        if (model.serviceUUID == service.UUID) {
            
            for (int row = 0; row<service.characteristics.count ; row++) {
                CBCharacteristic *c = service.characteristics[row];
                [model.characteristics addObject:c];
                NSLog(@"c.UUID:%@",c.UUID);
            }
        }
    }
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self.peripheralInfoTableView reloadData];
    });
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
{
    [AZProgressHUD showInfoWithStatus:@"蓝牙断开连接，请重新连接"];
    [self.services removeAllObjects];
    [self.peripheralInfoTableView reloadData];
}
// 这里只是实现中心管理者的代理方法，没其他意思
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    
}
-(void)dealloc
{
    [self.ble.cMgr cancelPeripheralConnection:self.currPeripheral];
    NSLog(@"断开链接");
    [AZProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@">>>断开<%@>的设备连接",self.currPeripheral.name]];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    AZPeripheralInfoModel *model = self.services[section];
    return model.characteristics.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.services.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    AZPeripheralInfoModel *model = self.services[section];
    return  [NSString stringWithFormat:@"%@",model.serviceUUID];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AZServiceCell *cell = [tableView dequeueReusableCellWithIdentifier:serviceCell];
    AZPeripheralInfoModel *model = self.services[indexPath.section];
    CBCharacteristic *c = model.characteristics[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",c.UUID];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AZCharacteristicViewController * characteristicVc = [AZCharacteristicViewController new];
    characteristicVc.peripheral = self.currPeripheral;
    AZPeripheralInfoModel *service = self.services[indexPath.section];
    characteristicVc.characteristic = service.characteristics[indexPath.row];
    [self.navigationController pushViewController:characteristicVc animated:YES];
}
@end
